<template>
  <div class="dish-container">
    <!-- 顶部标题和搜索区域 -->
    <div class="header">
      <h1>酒店餐饮管理系统</h1>
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入菜品名称"
          clearable
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="handleSearch"
          ></el-button>
        </el-input>
      </div>
    </div>

    <!-- 菜品展示区域 -->
    <div class="dish-list">
      <el-row :gutter="20">
        <el-col
          v-for="dish in dishList"
          :key="dish.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
        >
          <el-card class="dish-card" shadow="hover">
            <div class="dish-image-container">
              <img
                v-if="dish.imageUrl"
                :src="dish.imageUrl"
                class="dish-image"
                alt="菜品图片"
              />
              <div v-else class="image-placeholder">
                <i class="el-icon-picture-outline"></i>
                <span>暂无图片</span>
              </div>
              <div class="recommended-tag" v-if="dish.isRecommended === 1">
                推荐菜品
              </div>
              <div class="status-tag" :class="{ 'status-off': dish.status === 0 }">
                {{ dish.status === 1 ? '在售' : '已下架' }}
              </div>
            </div>
            <div class="dish-info">
              <h3>{{ dish.name }}</h3>
              <div class="price">¥{{ dish.price.toFixed(2) }}</div>
              <div class="category">
                分类: {{ getCategoryName(dish.categoryId) }}
              </div>
              <p class="description">{{ dish.description }}</p>
            </div>
            <div class="actions">
              <el-button
                :type="isDishCollected(dish.id) ? 'success' : 'default'"
                :icon="isDishCollected(dish.id) ? 'el-icon-star-on' : 'el-icon-star-off'"
                @click="toggleCollection(dish.id)"
                class="collect-btn"
              >
                {{ isDishCollected(dish.id) ? '已收藏' : '收藏' }}
              </el-button>
              <el-button
                type="primary"
                icon="el-icon-shopping-cart-full"
                :disabled="dish.status === 0"
                @click="showQuantityDialog(dish)"
              >
                加入购物车
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页控件 -->
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, total"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      >
      </el-pagination>
    </div>

    <!-- 数量选择弹窗 -->
    <el-dialog
      title="选择购买数量"
      :visible.sync="quantityDialogVisible"
      width="30%"
      :before-close="handleDialogClose"
    >
      <div v-if="currentDish">
        <div class="dialog-content">
          <img
            v-if="currentDish.imageUrl"
            :src="currentDish.imageUrl"
            class="dialog-image"
            alt="菜品图片"
          />
          <div class="dialog-info">
            <h3>{{ currentDish.name }}</h3>
            <div class="price">¥{{ currentDish.price.toFixed(2) }}</div>
            <div class="category">
              分类: {{ getCategoryName(currentDish.categoryId) }}
            </div>
          </div>
        </div>
        
        <div class="quantity-control">
          <span>购买数量:</span>
          <el-input-number
            v-model="purchaseQuantity"
            :min="1"
            :step="1"
            :controls-position="right"
          ></el-input-number>
        </div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="quantityDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddToCart">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listDish } from '@/api/Dish.js'
import { listDishcategory } from '@/api/Dishcategory.js'
import { addCollection, delCollectionInfo, listCollection } from '@/api/Collection.js'
import { addDishcart } from '@/api/Dishcart.js'
import { getToken, getUserId } from '@/utils/auth.js'
import { mapState } from 'vuex';

export default {
  name: 'DishList',
  data() {
    return {
      searchKeyword: '', // 搜索关键字
      dishList: [], // 菜品列表
      categoryMap: {}, // 分类映射（categoryId -> name）
      total: 0, // 总记录数
      pageSize: 10, // 每页显示条数
      currentPage: 1, // 当前页码
      userId: null, // 当前用户ID
      collectedDishes: [], // 已收藏的菜品ID列表
      
      // 新增购物车数量选择相关变量
      quantityDialogVisible: false, // 数量选择弹窗显示状态
      currentDish: null, // 当前操作的菜品
      purchaseQuantity: 1 // 购买数量，默认1
    }
  },
  mounted() {
    // 检查登录状态
    this.checkLoginStatus()
    // 获取菜品分类信息
    this.loadCategories()
    // 加载用户收藏列表
    this.fetchCollections()
    // 加载菜品数据
    this.loadDishes()
  },
  computed:{
        ...mapState('cart', ['cartItemCount'])
  },
  methods: {
    // 检查登录状态
    checkLoginStatus() {
      if (!getToken()) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }
      this.userId = getUserId()
    },
    
    // 加载菜品分类信息
    async loadCategories() {
      // 在实际项目中，这里应该获取所有分类
      // 为简化，这里使用硬编码分类映射
      this.categoryMap = {
        1: '热菜',
        2: '凉菜',
        3: '汤类',
        4: '主食',
        5: '饮料'
      }
      
      // 实际项目中应使用API获取
      
      try {
        const response = await listDishcategory({ pageNum: 1, pageSize: 100 })
        if (response.code === 200) {
          response.rows.forEach(category => {
            this.categoryMap[category.id] = category.name
          })
        }
      } catch (error) {
        console.error('获取分类失败:', error)
      }
      
    },
    
    // 根据分类ID获取分类名称
    getCategoryName(categoryId) {
      return this.categoryMap[categoryId] || '未知分类'
    },
    
    // 加载菜品数据
    async loadDishes() {
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          name: this.searchKeyword
        }
        
        const response = await listDish(params)
        if (response.code === 200) {
          this.dishList = response.rows.map(dish => {
            return {
              ...dish,
              // 根据收藏列表设置初始收藏状态
              collected: this.collectedDishes.includes(dish.id)
            }
          })
          this.total = response.total
        } else {
          this.$message.error(response.msg || '获取菜品列表失败')
        }
      } catch (error) {
        console.error('加载菜品失败:', error)
        this.$message.error('获取菜品信息失败')
      }
    },
    
    // 获取用户收藏的菜品列表
    async fetchCollections() {
      if (!this.userId) return
      
      try {
        const params = {
          userId: this.userId,
          itemType: 3 // 3表示菜品类型
        }
        
        const response = await listCollection(params)
        this.collectedDishes = response.rows.map(item => item.itemId) || []
      } catch (error) {
        console.error('获取收藏列表失败:', error)
        this.$message.error('获取收藏列表失败')
      }
    },
    
    // 检查菜品是否已被收藏
    isDishCollected(dishId) {
      return this.collectedDishes.includes(dishId)
    },
    
    // 切换菜品收藏状态
    async toggleCollection(dishId) {
      if (!this.userId) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }
      
      try {
        const data = {
          userId: this.userId,
          itemType: 3, // 菜品类型为3
          itemId: dishId
        }
        
        if (this.isDishCollected(dishId)) {
          // 取消收藏
          await delCollectionInfo(data)
          // 从收藏列表中移除
          this.collectedDishes = this.collectedDishes.filter(id => id !== dishId)
          this.$message.success('已取消收藏')
        } else {
          // 添加收藏
          await addCollection(data)
          // 添加到收藏列表
          this.collectedDishes.push(dishId)
          this.$message.success('收藏成功')
        }
        
        // 更新菜品列表中的收藏状态
        this.dishList = this.dishList.map(dish => ({
          ...dish,
          collected: this.isDishCollected(dish.id)
        }))
      } catch (error) {
        console.error('收藏操作失败:', error)
        this.$message.error('操作失败，请稍后重试')
      }
    },
    
    // 处理搜索
    handleSearch() {
      this.currentPage = 1
      this.loadDishes()
    },
    
    // 处理分页变化
    handlePageChange(page) {
      this.currentPage = page
      this.loadDishes()
    },
    
    // 显示数量选择弹窗
    showQuantityDialog(dish) {
      if (!this.userId) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }
      
      if (dish.status === 0) {
        this.$message.warning('该菜品已下架')
        return
      }
      
      // 重置数量为1并显示弹窗
      this.currentDish = dish
      this.purchaseQuantity = 1
      this.quantityDialogVisible = true
    },
    
    // 关闭弹窗时重置数据
    handleDialogClose() {
      this.currentDish = null
      this.purchaseQuantity = 1
      this.quantityDialogVisible = false
    },
    
    // 确认加入购物车
    async confirmAddToCart() {
      if (!this.currentDish) return
      
      try {
        const data = {
          userId: this.userId,
          dishId: this.currentDish.id,
          quantity: this.purchaseQuantity // 使用用户选择的数量
        }
        
        const response = await addDishcart(data)
        if (response.code === 200) {
          this.$message.success(`已加入${this.purchaseQuantity}份到购物车`)
          this.quantityDialogVisible = false
          // 核心逻辑：计算新的购物车数量并更新到 Vuex
          // 新数量 = 当前购物车数量 + 本次添加的数量
          const newCount = this.cartItemCount + 1;
          this.$store.dispatch('cart/updateCartCount', newCount);
        } else {
          this.$message.error(response.msg || '加入购物车失败')
        }
      } catch (error) {
        console.error('加入购物车失败:', error)
        this.$message.error('加入购物车失败')
      }
    }
  }
}
</script>

<style scoped>
.dish-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header h1 {
  color: #409EFF;
  font-size: 24px;
  margin: 0;
}

.search-area {
  width: 400px;
}

.dish-list {
  margin-top: 20px;
}

.dish-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: transform 0.3s;
}

.dish-card:hover {
  transform: translateY(-5px);
}

.dish-image-container {
  position: relative;
  height: 180px;
  overflow: hidden;
  border-radius: 6px 6px 0 0;
}

.dish-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.dish-card:hover .dish-image {
  transform: scale(1.05);
}

.image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 14px;
}

.image-placeholder i {
  font-size: 48px;
  margin-bottom: 10px;
}

.recommended-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #ff4d4f;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status-tag {
  position: absolute;
  top: 10px;
  left: 10px;
  background: #52c41a;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-tag.status-off {
  background: #909399;
}

.dish-info {
  padding: 15px;
}

.dish-info h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.price {
  color: #ff5000;
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0;
}

.category {
  color: #606266;
  font-size: 14px;
  margin: 5px 0;
}

.description {
  color: #909399;
  font-size: 13px;
  margin: 10px 0;
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  
  -webkit-box-orient: vertical;
}

.actions {
  display: flex;
  justify-content: space-between;
  padding: 0 15px 15px;
  gap: 10px;
}

.actions .el-button--text {
  color: #606266;
}

.collect-btn {
  flex: 1;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 弹窗样式 */
.dialog-content {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}

.dialog-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 6px;
  margin-right: 15px;
}

.dialog-info {
  flex: 1;
}

.quantity-control {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.quantity-control span {
  margin-right: 15px;
  font-size: 14px;
  color: #606266;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header h1 {
    margin-bottom: 15px;
  }
  
  .search-area {
    width: 100%;
  }
  
  .dialog-content {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .dialog-image {
    margin-bottom: 15px;
  }
}
</style>